//
//  HMStatusDAL.swift
//  Weibo
//
//  Created by Apple on 2017/7/17.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit

//  删除一周的缓存数据
let limitTime: Double = 7 * 24 * 3600

//  数据库访问层，用于封装缓存和查询微博数据的相关操作
class HMStatusDAL: NSObject {

    /*
        微博缓存流程
        1. 判断本地是否有缓存数据
        2. 如果本地有缓存数据直接返回本地数据
        3. 如果本地没有缓存数据从网络加载微博数据
        4. 网络加载微博数据成功后把数据缓存到本地
        5. 本地数据缓存成功后返回网络加载的数据
     */
    
    //  检查本地缓存数据
    class func checkCacheData(maxId: Int64, sinceId: Int64) -> [[String: Any]] {
        let userid = HMUserAccountViewModel.sharedUserAccount.userAccount?.uid
        var sql = "select * from statuses\n"
        if maxId > 0 {
            sql += "where id < \(maxId)\n"
        } else {
            sql += "where id > \(sinceId)\n"
        }
        sql += "and userid = \(userid!)\n"
        sql += "order by id desc limit 20\n"
        
        let dicArray = HMSqliteManager.sharedManager.selectDicArray(sql: sql)
        var tempArray = [[String: Any]]()
        for dic in dicArray {
            //  微博数据二进制
            let statusData = dic["status"] as! Data
            //  微博反序列化
            let statusDic = try! JSONSerialization.jsonObject(with: statusData, options: []) as! [String: Any]
            tempArray.append(statusDic)
        }
        return tempArray
    }
    
    //  缓存微博数据
    class func cacheData(statusDicArray: [[String: Any]]) {
        let sql = "insert into statuses(id, status, userid) values(?, ?, ?);"
        let userid = HMUserAccountViewModel.sharedUserAccount.userAccount?.uid
        HMSqliteManager.sharedManager.inTransaction { (db, rollBack) in
            for statusDic in statusDicArray {
                let id = statusDic["id"] as! Int64
                let statusData = try! JSONSerialization.data(withJSONObject: statusDic, options: [])
                let result = db?.executeUpdate(sql, withArgumentsIn: [id, statusData, userid!])
                if result == false {
                    //  回滚
                    rollBack?.pointee = true
                    break
                }
            }
        }
    }
    
    //  删除缓存数据
    class func clearCacheData() {
        let sql = "delete from statuses where time < ?"
        let dt = DateFormatter()
        dt.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let limitDate = Date().addingTimeInterval(-limitTime)
        let limitDateStr = dt.string(from: limitDate)
        HMSqliteManager.sharedManager.inDatabase { (db) in
            let result = db?.executeUpdate(sql, withArgumentsIn: [limitDateStr])
            if result == true {
                print("缓存数据删除成功，影响了\(db!.changes())条微博数据")
            } else {
                print("缓存数据删除失败")
            }
        }
    }
    
}
